var express = require('express');
var router = express.Router();
var mongo = require("./db");
// 处理mongodb id问题
var mongodb = require("mongodb");
var ObjectId = mongodb.ObjectId;

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

// 添加接口  
router.post("/add", function (req, res) {
  // 整理好前端传来的要添加到数据库的数据
  var obj = {
    nickname: req.body.nickname,
    msg: req.body.msg,
    imgsrc: req.body.imgsrc,
    date: new Date().toLocaleString(),
    zan: 0,
    cai: 0
  }
  // 
  mongo("insert", "msglist", obj, function () {
    res.send({ success: "添加成功" })
  })
})
// 查询所有留言数据接口
router.post("/all", function (req, res) {
  mongo("find", "msglist", {}, function (data) {
    res.send(data.reverse())
  })
})
// 删除接口
router.post("/del", function (req, res) {
  mongo("del", "msglist", { _id: ObjectId(req.body.id) }, function () {
    res.send({ success: "删除成功" })
  })
})
// 赞和踩接口
router.post("/zanAndCai", function (req, res) {
  if (req.body.action == "zan") {
    mongo("update", "msglist", [{ _id: ObjectId(req.body.id) }, { zan: req.body.zan }], function () {
      res.send({ success: "点赞成功" })
    })
  } else if (req.body.action == "cai") {
    mongo("update", "msglist", [{ _id: ObjectId(req.body.id) }, { cai: req.body.cai }], function () {
      res.send({ success: "点踩成功" })
    })
  }

})



module.exports = router;
